package com.apy.accountbook

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.util.Log
import android.widget.RemoteViews

class AccountWidget : AppWidgetProvider() {

    override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray
    ) {
        Log.e("AccountWidget","onUpdate")
        for (appWidgetId in appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId)
        }
        // 通知ListView刷新数据
        appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.lv_records)
    }

    override fun onReceive(context: Context, intent: Intent) {
        super.onReceive(context, intent)
        Log.e("AccountWidget","收到广播")
        // 接收到数据更新广播时刷新小部件
        if (intent.action == "com.apy.accountbook.ACTION_DATA_UPDATED") {
            val appWidgetManager = AppWidgetManager.getInstance(context)
            val appWidgetIds = appWidgetManager.getAppWidgetIds(
                ComponentName(context, AccountWidget::class.java)
            )
            // 更新小部件
            onUpdate(context, appWidgetManager, appWidgetIds)
            // 通知ListView刷新数据
            appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.lv_records)
        }
    }

    @SuppressLint("RemoteViewLayout")
    private fun updateAppWidget(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetId: Int
    ) {
        val views = RemoteViews(context.packageName, R.layout.widget_account)

        // Set up the button click event
        val intent = Intent(context, AddRecordActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            context,
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        views.setOnClickPendingIntent(R.id.btn_add_record, pendingIntent)

        val adapterIntent = Intent(context, WidgetService::class.java)
        views.setRemoteAdapter(R.id.lv_records, adapterIntent)

        appWidgetManager.updateAppWidget(appWidgetId, views)
        Log.d("AccountWidget", "Widget updated for appWidgetId: $appWidgetId")
    }
}